// pages/card/card.js
var config = require('../../config');
var util = require('../../utils/util.js');
var app = getApp();
// 开发时用本地数据测试-调用接口按card的id查询贺卡的纤细数据（返回的为它的styleType类型的对象）
var card_data = {};
Page({
  /**
   * 页面的初始数据
   */
  data: {
    host: config.service.host + '/',
    showEdit: 'displayNone', // 表单默认不展示
    showContentText: 'displayNone', // 动画祝福语默认不展示
    openMailZindex: 100,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var self = this;
    if (options.param) {
      this.shareParamList = options.param.split('`');
      app.globalData.cardInfo.id = this.shareParamList[3];
    }
    wx.request({
      url: config.service.card_data,
      method: "POST",
      data: { id: app.globalData.cardInfo.id },
      success(result) {
        card_data.info = result.data.card[0];
        card_data.images = self.getImgList(result.data.images);
        card_data.wishes = result.data.wishList;
        card_data.info.scroll = card_data.info.scroll == 1 ? true : false;
        console.log(card_data);
        if (self.shareParamList) {
          card_data.info.title_back = card_data.info.title; // 备份title，用于表单数据回显
          card_data.info.wish_content_back = card_data.info.wish_content; // 备份wish，用于表单数据回显
          card_data.info.wish_content = self.shareParamList[0];
          card_data.sendUser = self.shareParamList[1];
          card_data.receiveUser = self.shareParamList[2];
          card_data.info.title = self.shareParamList[4];
        }
        wx.setNavigationBarTitle({
          title: card_data.info.title // 页面标题为路由参数
        });
        self.setData({
          cardData: card_data
        });
        app.getUserInfo(function (userInfo) {
          var wishData = self.getWishData(card_data.wishes);
          self.setData({
            title: card_data.info.title_back || card_data.info.title,
            sendUser: userInfo.nickName || '', // 表单的发送人是自己
            receiveUser: '',
            content: (card_data.info.wish_content_back || card_data.info.wish_content).replace(new RegExp("<br>", "g"), '\n'),
            wishList: wishData.wishList,
            wishIndex: wishData.wishIndex
          });
        });
      },
      fail(error) {
        util.showModel('请求失败，请重试！', error);
      }
    });
    this.audioCtx = wx.createAudioContext('music'); // 加载音乐
    this.audioCtx.pause(); // 音乐加载后先不播放
    this.musicClickChange = 0; // 控制音乐点击暂停变量
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    this.setData({
      showEdit: 'displayNone'
    });
    var reObj = {
      title: this.data.title + '-收到来自' + this.data.sendUser + '的祝福',
      path: '/pages/card/card?param=' + this.data.content + '`' + this.data.sendUser + '`' + this.data.receiveUser + '`' + app.globalData.cardInfo.id + '`' + this.data.title
    }
    if (card_data.info.share_url) {
      reObj.imageUrl = this.data.host + card_data.info.share_url;
    }
    return reObj;
  },

  /**
   * 点击音乐图片
   */
  clickMusic: function () {
    this.musicAnimation();
  },

  /**
   * 音乐图片动画暂停继续
   */
  musicAnimation: function () {
    if (this.musicClickChange) {
      this.setData({
        musicRotation: ''
      });
      this.audioCtx.pause();
      this.musicClickChange = 0;
      return;
    }
    this.audioCtx.play();
    this.musicClickChange = 1;
    this.setData({
      musicRotation: 'musicRotation'
    });
  },

  /**
   * 打开信封动画
   */
  clickMail: function () {
    var cmAnimation = wx.createAnimation({
      transformOrigin: '50% 5% 0'
    });
    cmAnimation.rotateX(-150).step();
    this.setData({
      cmAnimation: cmAnimation.export()
    });
    var self = this;
    var bckAnimation = wx.createAnimation();
    bckAnimation.top(-345).step();
    setTimeout(function () {
      self.setData({
        openMailZindex: 98,
        bckAnimation: bckAnimation.export()
      });
    }, 800);
    setTimeout(function () {
      self.getFloatImg(); // 启动漂浮的图片
      self.musicAnimation(); // 启动音乐动画及播放音乐
    }, 1300);
    setTimeout(function () {
      self.setData({
        mailShow: 'displayNone',
      });
      self.creatImageAnimation(card_data.images, 0); // 加载动画，默认加载第一页的
    }, 1800);
  },

  /**
   * 或得漂浮图片数据
   */
  getFloatImg: function () {
    if (!card_data.info.float_url) return;
    // 获取随机数（float）
    var randomFloat = function (low, high) {
      return low + Math.random() * (high - low);
    }
    // 获取随机数（int）
    var randomInteger = function (low, high) {
      return low + Math.floor(Math.random() * (high - low));
    }
    var floatImgList = [];
    for (var i = 0; i < 10; i++) {
      var vLeft = randomInteger(0, app.globalData.clientWidth) + 'px';
      var fadeAndDropDuration = randomFloat(5, 11);
      var vDuration = fadeAndDropDuration + 's, ' + fadeAndDropDuration + 's';
      var leafDelay = randomFloat(0, 5);
      var vDelay = leafDelay + 's, ' + leafDelay + 's';
      var spinDuration = randomFloat(4, 8) + 's';
      floatImgList.push({
        vLeft: vLeft,
        vDuration: vDuration,
        vDelay: vDelay,
        iName: (Math.random() < 0.5) ? 'clockwiseSpin' : 'counterclockwiseSpinAndFlip',
        iDuration: spinDuration
      });
    }
    this.setData({
      floatImgList: floatImgList
    });
  },

  /**
   * 查看更多按钮
   */
  lookMore: function () {
    wx.switchTab({
      url: '../kind/kind'
    })
  },

  /**
   * 编，取消编辑功能
   */
  editClick: function () {
    this.setData({
      showEdit: this.data.showEdit ? '' : 'displayNone'
    });
  },

  /**
   * 提交表单
   */
  formSubmit: function (e) {
    wx.setNavigationBarTitle({
      title: e.detail.value.title // 页面标题为路由参数
    });
    this.setData({
      title: e.detail.value.title,
      sendUser: e.detail.value.sendUser,
      receiveUser: e.detail.value.receiveUser,
      content: e.detail.value.content,
      contentText: this.fmtContent(e.detail.value.content, e.detail.value.receiveUser, e.detail.value.sendUser, '\n'),
      isSubmit: true
    });
  },

  /**
   * 祝福语下拉选择
   */
  bindPickerChange: function (e) {
    this.setData({
      content: card_data.wishes[e.detail.value].content.replace(new RegExp("<br>", "g"), '\n')
    });
  },

  /**
   * 祝福语文字处理
   */
  fmtContent: function (param, receiveUser, sendUser, flag) {
    param = '亲爱的' + (receiveUser || '朋友') + `：${flag}  ` + param;
    param += flag + sendUser;
    var fmtText = param.split(flag), maxLength = 0;
    fmtText.forEach(function (item) {
      maxLength = item.length > maxLength ? item.length : maxLength;
    });
    this.setData({
      contentWidth: 20 * maxLength > app.globalData.clientWidth ? 'auto' : 20 * maxLength + 'px'
    });
    var sjIndex = 0;
    fmtText.forEach(function (item, index) {
      var l = item.length;
      if (l < maxLength) {
        for (var i = 0; i < maxLength - l; i++) {
          item += ' ';
        }
      }
      var textList = item.split('');
      textList.forEach(function (item, index) {
        sjIndex = item != ' ' ? sjIndex + 1 : sjIndex;
        textList[index] = {
          value: item,
          index: sjIndex
        }
      });
      fmtText[index] = textList;
    });
    var lastRow = fmtText[fmtText.length - 1];
    var hasV = lastRow.filter(function (item) {
      return item.value != ' ';
    });
    var noV = lastRow.filter(function (item) {
      return item.value == ' ';
    });
    fmtText[fmtText.length - 1] = noV.concat(hasV);
    return fmtText;
  },

  /**
   * 当切换页面时触发，防止飘的图片干扰二维码
   */
  currentIndex: function (e) {
    this.creatImageAnimation(card_data.images, e.detail.current);
    if (!this.data.showContentText) return;
    var wishIn = 0;
    for (var i = 0; i < card_data.images.length; i++) {
      if (card_data.images[i].wishIn == 1) {
        wishIn = i;
        break;
      }
    }
    if (e.detail.current == wishIn) {
      this.setData({
        showContentText: '',
        contentText: this.fmtContent(card_data.info.wish_content, card_data.receiveUser, card_data.sendUser || this.data.sendUser, this.shareParamList ? '\n' : '<br>')
      });
    }
  },

  /**
   * 转化图片数组
   */
  getImgList: function (list) {
    var returnList = [];
    var bgd = list.filter(function (item) {
      return item.background == 1;
    });
    bgd.forEach(function (item) {
      returnList.push({
        url: item.url,
        wishIn: item.wish_in,
        list: list.filter(function (i) {
          return i.image == item.id;
        })
      });
    });
    return returnList;
  },

  /**
   * 解析图片动画，一个页面最多支持10个动画图片
   */
  creatImageAnimation: function (list, page) {
    if (this.data[`imageAnimation${page}0`]) return;
    var self = this;
    list.forEach(function (images, imagesIndex) {
      if (page != imagesIndex) return;
      images.list.forEach(function (item, itemIndex) {
        if (!item.animation) return;
        var animationObj = null;
        try {
          animationObj = JSON.parse(item.animation);
        } catch (e) {
          return;
        }
        if (typeof animationObj != 'object' || typeof animationObj.animation != 'object') return;
        self.loopAnimation = function(a, styleList, index0, index1) {
          var dataObj = {};
          for (var i in styleList) {
            a[i] && a[i].apply(a, (styleList[i] + '').split(', '));
          }
          a.step();
          dataObj[`imageAnimation${index0}${index1}`] = a.export();
          self.setData(dataObj);
        }
        self.loopAnimation(self.createAnimationObj(animationObj), animationObj.animation, imagesIndex, itemIndex); // 默认第一次，用from
        if (animationObj.animationIterationCount == 1) return;
        var toAnimationObj = item.style.replace(/; /g, '", "');
        toAnimationObj = toAnimationObj.replace(/: /g, '": "');
        toAnimationObj = '{"' + toAnimationObj.substr(0, toAnimationObj.length - 1) + '"}';
        try {
          toAnimationObj = JSON.parse(toAnimationObj);
          for (var i in toAnimationObj) {
            if (!animationObj.animation[i]) delete toAnimationObj[i];
          }
        } catch (e) {
          return;
        }
        var intervalParam = {
          animationIterationCount: animationObj.animationIterationCount,
          imagesIndex: imagesIndex,
          itemIndex: itemIndex,
          toAnimationObj: toAnimationObj,
          fromAnimationObj: animationObj.animation
        }
        var animationInterval = function(param, time) {
          var that = this, count = 0;
          that.intervalParam = param;
          var intervalCount = setInterval(function() {
            var obj = count % 2 ? that.intervalParam.fromAnimationObj : that.intervalParam.toAnimationObj;
            self.loopAnimation(self.createAnimationObj(animationObj), obj, that.intervalParam.imagesIndex, that.intervalParam.itemIndex);
            count++;
            if (that.intervalParam.animationIterationCount - 1 == count) {
              clearInterval(intervalCount);
            }
          }, time);
        }
        new animationInterval(intervalParam, animationObj.duration || 400); // 为图片创建动画，每个图片是独立的动画
      });
    });
  },

  createAnimationObj: function(obj) {
    return wx.createAnimation({
      duration: obj.duration - 0 || 400,
      timingFunction: obj.timingFunction || 'linear',
      delay: obj.delay - 0 || 0,
      transformOrigin: obj.transformOrigin || '50% 50% 0'
    });
  },

  /**
   * 得到祝福语下拉的数据
   */
  getWishData: function (list) {
    var returnData = {
      wishList: [],
      wishIndex: 0
    };
    for (var i = 0; i < list.length; i++) {
      if (list[i].id == card_data.info.wish) {
        returnData.wishIndex = i;
      }
      returnData.wishList.push(list[i].mini);
    }
    return returnData;
  }
})